/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package station;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

/**
 *
 * @author safe
 */
public class MulticastListener extends Thread {

    private MulticastSocket multicastSocket;

    protected MulticastListener(MulticastSocket multicastSocket) {
        this.multicastSocket = multicastSocket;
    }
    
    private int extractMessageSlotNumber(byte[] message) {
        return (int) message[25];
    }

    @Override
    public void run() {

        byte[] nachricht = new byte[DataNaechsteNachricht.MESSAGE_LENGTH];
        DatagramPacket datagram = new DatagramPacket(nachricht, nachricht.length);
        long synchronisierteEmpfangsZeit;
        while (!this.isInterrupted()) {

            try {
                multicastSocket.receive(datagram);
                int reservedSlotNumber = this.extractMessageSlotNumber(datagram.getData());
                synchronisierteEmpfangsZeit = System.currentTimeMillis() + DataAbweichungsZeit.getAbWeichungsZeit();
                DataSlotBelegung.setSlotReserved(reservedSlotNumber);
                StationUpdateWorker worker = new StationUpdateWorker(synchronisierteEmpfangsZeit, nachricht);
                worker.start();
            } catch (IOException ex) {
//                Logger.getLogger(MulticastListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
